package org.nmgyjt.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nimbusds.jose.JOSEException;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.CsSystemIDSelectBean;
import org.nmgyjt.springboot.beans.admin.StatisticBean;
import org.nmgyjt.springboot.beans.vo.PageVo;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.CsSystemDeptResponse;
import org.nmgyjt.springboot.entity.materials.Materials;
import org.nmgyjt.springboot.entity.refuge.RefugeInfo;
import org.nmgyjt.springboot.entity.rescueTeam.RescueTeam;
import org.nmgyjt.springboot.entity.sms.YuFuMSSendEntity;
import org.nmgyjt.springboot.entity.storeInfo.StoreInfo;
import org.nmgyjt.springboot.mapper.CsSystemAdminMapper;
import org.nmgyjt.springboot.mapper.MaterialsMapper;
import org.nmgyjt.springboot.mapper.StoreMapper;
import org.nmgyjt.springboot.service.ICsSystemDeptService;
import org.nmgyjt.springboot.service.MaterialsService;
import org.nmgyjt.springboot.service.StoreService;
import org.nmgyjt.springboot.utils.ZWWXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.util.*;

@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, StoreInfo> implements StoreService {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private MaterialsMapper materialsMapper;
    @Autowired
    private StoreService storeService;
    @Autowired
    private MaterialsService materialsService;
    @Autowired
    private ICsSystemDeptService iCsSystemDeptService;
    @Autowired
    SendSMSServiceImpl smsService;
    @Autowired
    CsSystemAdminMapper csSystemAdminMapper;
    @Autowired
    ZWWXUtils zwwxUtils;

    @Override
    public StoreInfo getById(Long id, String firstType) {
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        StoreInfo storeInfo = storeMapper.selectOne(queryWrapper);
        QueryWrapper<Materials> materialsQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(storeInfo)) {
            materialsQueryWrapper.eq("store_id", storeInfo.getId());
            materialsQueryWrapper.eq("first_store_type", "01");
//            List<Materials> materialsList = materialsMapper.selectList(materialsQueryWrapper);
//            storeInfo.setMaterialsList1(materialsList);

            storeInfo.setProtectNum(materialsMapper.selectCount(materialsQueryWrapper));
            materialsQueryWrapper.clear();
            materialsQueryWrapper.eq("store_id", storeInfo.getId());
            materialsQueryWrapper.eq("first_store_type", "02");
//            storeInfo.setMaterialsList2(materialsMapper.selectList(materialsQueryWrapper));
            storeInfo.setFloodNum(materialsMapper.selectCount(materialsQueryWrapper));
            materialsQueryWrapper.clear();
            materialsQueryWrapper.eq("store_id", storeInfo.getId());
            materialsQueryWrapper.eq("first_store_type", "03");
//            storeInfo.setMaterialsList3(materialsMapper.selectList(materialsQueryWrapper));
            storeInfo.setShockproofNum(materialsMapper.selectCount(materialsQueryWrapper));
            materialsQueryWrapper.clear();
            materialsQueryWrapper.eq("store_id", storeInfo.getId());
            materialsQueryWrapper.eq("first_store_type", "04");
//            storeInfo.setMaterialsList4(materialsMapper.selectList(materialsQueryWrapper));
            storeInfo.setDisasterNum(materialsMapper.selectCount(materialsQueryWrapper));
            materialsQueryWrapper.clear();
            materialsQueryWrapper.eq("store_id", storeInfo.getId());
            materialsQueryWrapper.eq("first_store_type", "05");
//            storeInfo.setMaterialsList5(materialsMapper.selectList(materialsQueryWrapper));
            storeInfo.setOtherNum(materialsMapper.selectCount(materialsQueryWrapper));
        }
        return storeInfo;
    }

    @Override
    public StoreInfo getBydepId(String depId) {
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state","1");
        StoreInfo storeInfo = null;
        try {
            storeInfo = storeMapper.selectOne(queryWrapper);
            QueryWrapper<Materials> materialsQueryWrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(storeInfo)) {
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "01");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum=0;
                for(Materials materials:materialsList){
                    materialsNum=materialsNum+materials.getStoreNum();
                }
//                storeInfo.setProtectNum(materialsMapper.selectCount(materialsQueryWrapper));
                storeInfo.setProtectNum(materialsNum);

                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "02");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList2 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum2=0;
                for(Materials materials:materialsList2){
                    materialsNum2=materialsNum2+materials.getStoreNum();
                }
    //            storeInfo.setMaterialsList2(materialsMapper.selectList(materialsQueryWrapper));
                storeInfo.setFloodNum(materialsNum2);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "03");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList3 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum3=0;
                for(Materials materials:materialsList3){
                    materialsNum3=materialsNum3+materials.getStoreNum();
                }
    //            storeInfo.setMaterialsList3(materialsMapper.selectList(materialsQueryWrapper));
                storeInfo.setShockproofNum(materialsNum3);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "04");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList4 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum4=0;
                for(Materials materials:materialsList4){
                    materialsNum4=materialsNum4+materials.getStoreNum();
                }
    //            storeInfo.setMaterialsList4(materialsMapper.selectList(materialsQueryWrapper));
                storeInfo.setDisasterNum(materialsNum4);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "05");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList5 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum5=0;
                for(Materials materials:materialsList5){
                    materialsNum5=materialsNum5+materials.getStoreNum();
                }
    //            storeInfo.setMaterialsList5(materialsMapper.selectList(materialsQueryWrapper));
                storeInfo.setOtherNum(materialsNum5);
            }
//            else {
//                StoreInfo storeInfo1 = storeMapper.selectOne(queryWrapper);
//                CsSystemIDSelectBean csSystemIDSelectBean = new CsSystemIDSelectBean();
//                csSystemIDSelectBean.setId(depId);
//                CsSystemDeptResponse detailCsSystemOrg = iCsSystemDeptService.detailCsSystemOrg(csSystemIDSelectBean);
//                if (!ObjectUtils.isEmpty(detailCsSystemOrg)) {
//                    storeInfo1.setStoreName(detailCsSystemOrg.getName());
//                }
//                return storeInfo1;
//            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return storeInfo;
    }

    @Override
    public PageVo<Materials> getStoreInfo(String id, String type, Page<Materials> page,String storeName) {
        QueryWrapper<Materials> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", id);
        queryWrapper.eq("first_store_type", type);
        queryWrapper.ne("state","1");
        if(!ObjectUtils.isEmpty(storeName)){
            queryWrapper.like("store_name","%"+storeName+"%");
        }
        Page<Materials> materialsPage = materialsMapper.selectPage(page, queryWrapper);
        PageVo<Materials> materialsPageVo = new PageVo<>();
        materialsPageVo.setTotal(materialsPage.getTotal());
        materialsPageVo.setList(materialsPage.getRecords());
        return materialsPageVo;
    }


    @Override
    public ApiRes insertOrUpdate(StoreInfo storeInfo) {
        try {
            boolean b=false;
            if(!ObjectUtils.isEmpty(storeInfo.getId())){
                StoreInfo storeInfo1=this.getById(storeInfo.getId());
                if(ObjectUtils.isEmpty(storeInfo1.getHeadPhone())){
                    b = true;
                }else{
                    if(!storeInfo1.getHeadPhone().equals(storeInfo.getHeadPhone())){
//                        String ssoAccessToken=zwwxUtils.getGovWxToken();
//                        Integer code=zwwxUtils.getZWUserInfo(storeInfo1.getHeadPhone(),null,ssoAccessToken);
                        b = true;
                    }
                }
            }
            int protectNum = 0;
            int floodNum = 0;
            int shockproofNum = 0;
            int disasterNum = 0;
            int otherNum = 0;
            List<Materials> materialsList = storeInfo.getMaterialsList();
            storeInfo.setState("0");
            storeService.saveOrUpdate(storeInfo);
            if (!ObjectUtils.isEmpty(storeInfo.getId()) && materialsList.size() > 0) {
                for (Materials materials : materialsList) {
                    materials.setStoreId(storeInfo.getId());
                    if(materials.getSecondStoreType().equals("被服类")){
                        materials.setSecondStoreTypeCode("01");
                    }
                    if(materials.getSecondStoreType().equals("安置类")){
                        materials.setSecondStoreTypeCode("02");
                    }
                    if(materials.getSecondStoreType().equals("装具类")){
                        materials.setSecondStoreTypeCode("03");
                    }
                    if(materials.getSecondStoreType().equals("装备类")){
                        materials.setSecondStoreTypeCode("04");
                    }
                    if(materials.getSecondStoreType().equals("其他类")){
                        materials.setSecondStoreTypeCode("05");
                    }
                    materials.setState("0");
                }
                //删除前端未传输的装备id数据
                if (!ObjectUtils.isEmpty(storeInfo.getIds())) {
//                    QueryWrapper<Materials> materialsQueryWrapper = new QueryWrapper<>();
                    String[] ids = storeInfo.getIds().split(",");
                    materialsMapper.deleteByIds(ids);
//                    List<String> idsList = new ArrayList<>();
//                    Collections.addAll(idsList, ids);
//                    materialsQueryWrapper.eq("store_id", storeInfo.getId());
//                    materialsQueryWrapper.in("id", idsList);
//                    materialsMapper.delete(materialsQueryWrapper);
                }
                materialsService.saveOrUpdateBatch(materialsList);
                QueryWrapper<Materials> materialsQueryWrapper = new QueryWrapper<>();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "01");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList1 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum=0;
                for(Materials materials:materialsList1){
                    materialsNum=materialsNum+materials.getStoreNum();
                }
//                protectNum = materialsMapper.selectCount(materialsQueryWrapper);
                storeInfo.setProtectNum(materialsNum);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "02");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList2 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum2=0;
                for(Materials materials:materialsList2){
                    materialsNum2=materialsNum2+materials.getStoreNum();
                }
//                floodNum = materialsMapper.selectCount(materialsQueryWrapper);
                storeInfo.setFloodNum(materialsNum2);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "03");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList3 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum3=0;
                for(Materials materials:materialsList3){
                    materialsNum3=materialsNum3+materials.getStoreNum();
                }
//                shockproofNum = materialsMapper.selectCount(materialsQueryWrapper);
                storeInfo.setShockproofNum(materialsNum3);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "04");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList4 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum4=0;
                for(Materials materials:materialsList4){
                    materialsNum4=materialsNum4+materials.getStoreNum();
                }
//                disasterNum = materialsMapper.selectCount(materialsQueryWrapper);
                storeInfo.setDisasterNum(materialsNum4);
                materialsQueryWrapper.clear();
                materialsQueryWrapper.eq("store_id", storeInfo.getId());
                materialsQueryWrapper.eq("first_store_type", "05");
                materialsQueryWrapper.ne("state","1");
                List<Materials> materialsList5 = materialsMapper.selectList(materialsQueryWrapper);
                int materialsNum5=0;
                for(Materials materials:materialsList5){
                    materialsNum5=materialsNum5+materials.getStoreNum();
                }
//                otherNum = materialsMapper.selectCount(materialsQueryWrapper);
                storeInfo.setOtherNum(materialsNum5);
                Boolean s=storeService.saveOrUpdate(storeInfo);
                //更新政微详情
                if(b&&s){
                    String ssoAccessToken=zwwxUtils.getGovWxToken();
                    Integer code = zwwxUtils.getZWUserInfo(storeInfo.getHeadPhone(),"supplies/supplies-detail?depId="+storeInfo.getDepId(),ssoAccessToken);
                    storeInfo.setSnycState(code.toString());
                    storeService.saveOrUpdate(storeInfo);
                    YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
                    List<String> params = new ArrayList<>();
                    List<String> phone = new ArrayList<>();
                    phone.add("+86"+storeInfo.getHeadPhone());
                    params.add(storeInfo.getHeadName());
                    params.add("物资仓库"+storeInfo.getStoreName());
                    sendEntity.setTemplateParamSet(params);
                    sendEntity.setPhoneNumSet(phone);
                    sendEntity.setType("notification");
                    smsService.sendMS(sendEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiRes.customFail("保存失败！");
        }
        return ApiRes.ok(storeInfo.getId());
    }

    @Override
    public ApiRes deleteByDepId(String depId) {
        QueryWrapper<StoreInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dep_id",depId);
        queryWrapper.ne("state","1");
        StoreInfo storeInfo=storeMapper.selectOne(queryWrapper);
        if(!ObjectUtils.isEmpty(storeInfo)){
            int num=storeMapper.deleteByDepId(storeInfo.getDepId());
            if(num>0){
                materialsMapper.deleteBystoreId(storeInfo.getId());
                return ApiRes.ok();
            }else{
                return ApiRes.customFail("删除失败");
            }
        }
        return ApiRes.ok();
    }

    @Override
    public Map<String, Object> getstoreStatistics(StatisticBean statisticBean) {
        QueryWrapper<CsSystemAdmin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",statisticBean.getCreatedBy());
        if(!ObjectUtils.isEmpty(statisticBean.getSuperOrgId())){
            queryWrapper.eq("superior_org", statisticBean.getSuperOrgId());
        }
        CsSystemAdmin csSystemAdmin=csSystemAdminMapper.selectOne(queryWrapper);
        Map<String, Object> retMap = new LinkedHashMap<>();
        if(ObjectUtils.isEmpty(csSystemAdmin)){
            return retMap;
        }
        String sql = " AND r.state <> '1'";
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            sql = sql + " AND a.superior_org='" + csSystemAdmin.getOrgId() + "'";
        }else{
            sql = sql + " AND a.superior_org='-1'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getName())) {
            sql = sql + " AND a.org_name like '%"+statisticBean.getName()+"%'";
        }

        String sql2 = "";
        if (StringUtils.isNotEmpty(statisticBean.getStatus())) {
            if ("1".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '0' ";
            }
            if ("2".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '2' ";
            }

        }
        List<Map<String, Object>> List = storeMapper.statisticStore(sql, sql2);

        List<Map<String, Object>> maplist = storeMapper.statisticStoreCount(csSystemAdmin.getOrgId());
        int doneCount=storeMapper.statisticStoreCountStatus(csSystemAdmin.getOrgId());
        int unDoneCount=maplist.size()-doneCount;
        Integer protect_num = 0;
        Integer flood_num = 0;
        Integer shockproof_num = 0;
        Integer disaster_num = 0;
        Integer other_num = 0;
        for (Map<String, Object> map : maplist) {
            protect_num += Integer.valueOf(String.valueOf(map.get("protect_num") == null ? 0 : map.get("protect_num")));
            flood_num += Integer.valueOf(String.valueOf(map.get("flood_num") == null ? 0 : map.get("flood_num")));
            shockproof_num += Integer.valueOf(String.valueOf(map.get("shockproof_num") == null ? 0 : map.get("shockproof_num")));
            disaster_num += Integer.valueOf(String.valueOf(map.get("disaster_num") == null ? 0 : map.get("disaster_num")));
            other_num += Integer.valueOf(String.valueOf(map.get("other_num") == null ? 0 : map.get("other_num")));
        }
        Integer storeNum = maplist.size();
        retMap.put("doneCount", doneCount);
        retMap.put("unDoneCount", unDoneCount);
        retMap.put("protect_num", protect_num);
        retMap.put("flood_num", flood_num);
        retMap.put("shockproof_num", shockproof_num);
        retMap.put("disaster_num", disaster_num);
        retMap.put("other_num", other_num);
        retMap.put("store_num", storeNum);
        retMap.put("list", List);
        return retMap;
    }

    @Override
    public void snycZwwxByHeadPhone() {
        QueryWrapper<StoreInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.isNotNull("head_phone");
        queryWrapper.ne("snyc_state","0");
        List<StoreInfo> storeInfoList=storeMapper.selectList(queryWrapper);
        for(StoreInfo storeInfo:storeInfoList){
            String ssoAccessToken=zwwxUtils.getGovWxToken();
            Integer code=zwwxUtils.getZWUserInfo(storeInfo.getHeadPhone(),"rescue/rescue-detail?depId="+storeInfo.getDepId(),ssoAccessToken);
            storeInfo.setSnycState(code.toString());
            this.saveOrUpdate(storeInfo);
        }
    }
}
